package com.lc.ibps.platform.rest.system;

import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lc.ibps.base.core.engine.script.GroovyScriptEngine;
import com.lc.ibps.base.core.util.AppUtil;
import com.lc.ibps.base.core.util.BeanUtils;
import com.lc.ibps.base.core.util.json.JsonUtil;
import com.lc.ibps.base.core.util.time.DateUtil;
import com.lc.ibps.cloud.entity.APIRequest;
import com.lc.ibps.cloud.entity.APIResult;
import com.lc.ibps.web.controller.BaseApiController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 公共的调用。 比如：调用Groovy脚本 获取当前时间等
 *
 * <pre>
 *  
 * 构建组：ibps-platform-appapi
 * 作者：hugh zhuang
 * 邮箱：3378340995@qq.com
 * 日期：2018年8月16日-上午9:24:14
 * 版权：广州流辰信息技术有限公司版权所有
 * </pre>
 */
@RequestMapping(value = "/api/webapi/commonService")
@Api(value = "/commonService", tags = "系统管理-公共数据服务")
@RestController
public class CommonController extends BaseApiController {

	/**
	 * 获取脚本的值
	 *
	 * @param script
	 * @throws Exception
	 */
	@ApiOperation(value = "获取脚本的值", notes = "获取脚本的值")
	@RequestMapping(value = "/getScriptValue", method = RequestMethod.POST)
	public APIResult<String> getScriptValue(
			@ApiParam(name = "request", value = "传入请求json字符串", required = true) 
			@RequestBody(required = true) APIRequest request) throws Exception {
		APIResult<String> result = new APIResult<String>();
		String script = request.getParameter("script");
		String vars = request.getParameter("vars");
		Object value = null;
		try {

			Map<String, Object> varsMap = null;
			if (BeanUtils.isNotEmpty(vars)) {
				varsMap = JsonUtil.getMapFromJson(vars);
			}
			GroovyScriptEngine groovyScriptEngine = (GroovyScriptEngine) AppUtil.getBean(GroovyScriptEngine.class);
			value = groovyScriptEngine.executeObject(script, varsMap);
			result.setData(value.toString());
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取脚本值失败", e);
		}
		return result;
	}

	/**
	 * 获取系统时间
	 *
	 * @param script
	 * @throws Exception
	 */
	@ApiOperation(value = "获取系统时间", notes = "获取系统时间")
	@RequestMapping(value = "/getSystemTimestamp", method = RequestMethod.GET)
	public APIResult<Long> getSystemTimestamp() throws Exception {
		APIResult<Long> result = new APIResult<>();
		try {
			result.setData(DateUtil.getCurrentTimeInMillis());
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "获取系统时间失败", e);
		}
		return result;
	}

}
